import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Input,
  Button,
  Space,
  Modal,
  Form,
  message,
  Tag,
  Popconfirm,
  Tooltip,
  Tree,
  Select,
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  FolderOutlined,
  FolderOpenOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getRolePermissions, UserRole } from '../types/user';

// 分类接口定义
interface Category {
  id: number;
  name: string;
  parentId: number | null;
  level: number;
  sort: number;
  status: 'active' | 'disabled';
  createdAt: string;
  updatedAt: string;
}

// 分类表单数据接口
interface CategoryFormData {
  name: string;
  parentId: number | null;
  sort: number;
  status: 'active' | 'disabled';
}

// 获取当前用户角色（临时实现）
const getCurrentUserRole = (): UserRole => {
  return UserRole.SUPER_ADMIN;
};

const CategoryManagement: React.FC = () => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [form] = Form.useForm();

  // 获取当前用户权限
  const currentUserRole = getCurrentUserRole();
  const currentUserPermissions = getRolePermissions(currentUserRole);

  // 检查是否有权限管理分类
  const canManageCategories = currentUserPermissions.canManageCategories;

  // 获取分类列表
  const fetchCategories = async () => {
    if (!canManageCategories) return;
    
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setCategories(mockCategories);
    } catch (error) {
      message.error('获取分类列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载 - 移到权限检查之前
  useEffect(() => {
    fetchCategories();
  }, [canManageCategories]); // 添加 canManageCategories 作为依赖

  // 如果没有权限，显示提示信息
  if (!canManageCategories) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px 0' }}>
          <h2>无权访问</h2>
          <p>您没有权限访问分类管理页面</p>
        </div>
      </Card>
    );
  }

  // 模拟数据
  const mockCategories: Category[] = [
    {
      id: 1,
      name: '电子产品',
      parentId: null,
      level: 1,
      sort: 1,
      status: 'active',
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-01T00:00:00Z',
    },
    {
      id: 2,
      name: '手机',
      parentId: 1,
      level: 2,
      sort: 1,
      status: 'active',
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-01T00:00:00Z',
    },
    {
      id: 3,
      name: '电脑',
      parentId: 1,
      level: 2,
      sort: 2,
      status: 'active',
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-01T00:00:00Z',
    },
    {
      id: 4,
      name: '服装',
      parentId: null,
      level: 1,
      sort: 2,
      status: 'active',
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-01T00:00:00Z',
    },
  ];

  // 打开新增分类弹窗
  const handleAdd = (parentId: number | null = null) => {
    setModalTitle('新增分类');
    setEditingCategory(null);
    form.resetFields();
    form.setFieldsValue({ parentId, status: 'active', sort: 0 });
    setModalVisible(true);
  };

  // 打开编辑分类弹窗
  const handleEdit = (category: Category) => {
    setModalTitle('编辑分类');
    setEditingCategory(category);
    form.setFieldsValue(category);
    setModalVisible(true);
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingCategory) {
        // 编辑分类
        message.success('更新分类成功');
      } else {
        // 新增分类
        message.success('创建分类成功');
      }
      setModalVisible(false);
      fetchCategories();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除分类
  const handleDelete = async (id: number) => {
    try {
      // 模拟删除操作
      await new Promise(resolve => setTimeout(resolve, 500));
      message.success('删除分类成功');
      fetchCategories();
    } catch (error) {
      message.error('删除分类失败');
    }
  };

  // 构建树形数据
  const buildTreeData = (categories: Category[]) => {
    const treeData = categories
      .filter(category => category.parentId === null)
      .map(category => ({
        key: category.id,
        title: (
          <Space>
            <span>{category.name}</span>
            <Space>
              <Tooltip title="添加子分类">
                <Button
                  type="link"
                  size="small"
                  icon={<PlusOutlined />}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleAdd(category.id);
                  }}
                />
              </Tooltip>
              <Tooltip title="编辑">
                <Button
                  type="link"
                  size="small"
                  icon={<EditOutlined />}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleEdit(category);
                  }}
                />
              </Tooltip>
              <Popconfirm
                title="确定要删除该分类吗？"
                onConfirm={(e) => {
                  e?.stopPropagation();
                  handleDelete(category.id);
                }}
                okText="确定"
                cancelText="取消"
              >
                <Tooltip title="删除">
                  <Button
                    type="link"
                    size="small"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={(e) => e.stopPropagation()}
                  />
                </Tooltip>
              </Popconfirm>
            </Space>
          </Space>
        ),
        children: categories
          .filter(child => child.parentId === category.id)
          .map(child => ({
            key: child.id,
            title: (
              <Space>
                <span>{child.name}</span>
                <Space>
                  <Tooltip title="添加子分类">
                    <Button
                      type="link"
                      size="small"
                      icon={<PlusOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleAdd(child.id);
                      }}
                    />
                  </Tooltip>
                  <Tooltip title="编辑">
                    <Button
                      type="link"
                      size="small"
                      icon={<EditOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleEdit(child);
                      }}
                    />
                  </Tooltip>
                  <Popconfirm
                    title="确定要删除该分类吗？"
                    onConfirm={(e) => {
                      e?.stopPropagation();
                      handleDelete(child.id);
                    }}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Tooltip title="删除">
                      <Button
                        type="link"
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={(e) => e.stopPropagation()}
                      />
                    </Tooltip>
                  </Popconfirm>
                </Space>
              </Space>
            ),
          })),
      }));

    return treeData;
  };

  return (
    <div className="category-management">
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => handleAdd()}
          >
            新增顶级分类
          </Button>
        </div>

        <Tree
          showLine={{ showLeafIcon: false }}
          showIcon
          defaultExpandAll
          treeData={buildTreeData(categories)}
        />
      </Card>

      {/* 新增/编辑分类弹窗 */}
      <Modal
        title={modalTitle}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="parentId"
            label="上级分类"
            hidden
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="sort"
            label="排序"
            rules={[{ required: true, message: '请输入排序值' }]}
          >
            <Input type="number" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Select.Option value="active">启用</Select.Option>
              <Select.Option value="disabled">禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CategoryManagement; 